import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:lottie/lottie.dart';
import 'package:ride_rex/article/comment.dart';
import 'package:ride_rex/article/detail/article_detail_logic.dart';
import 'package:ride_rex/generated/assets.dart';
import 'package:ride_rex/person_detail/person_detail_page.dart';
import 'package:ride_rex/route.dart';
import 'package:ride_rex/standard/app_colors.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import '../../main/discover/discover_bean.dart';
import '../../person_detail/person_detail_logic.dart';
import '../../ui/common_dialogs.dart';
import '../../voice_record/chat_voice_record_bar.dart';
import '../../voice_record/chat_voice_record_layout.dart';

class ArticleDetailPage extends GetView<ArticleDetailLogic> {
  ArticleDetailPage(this.bean, this.workBean, {super.key});

  final FeedUserBean bean;
  final FeedUserWorkBean workBean;

  final String _tag = DateTime.now().millisecondsSinceEpoch.toString();

  @override
  String? get tag => _tag;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ArticleDetailLogic>(
        init: ArticleDetailLogic(bean, workBean),
        tag: _tag,
        builder: (logic) {
          return ChatVoiceRecordLayout(
            onCompleted: (int fileDuration, String path, String fileName, int fileSize) {
              logic.sendAudioComment(path: path, fileName: fileName, duration: fileDuration, size: fileSize);
            },
            builder: (ChatVoiceRecordBar recordBar) {
              return BaseScaffold(
                safeAreaBottom: true,
                scaffoldBackgroundColor: Colors.white,
                child: Stack(
                  children: [
                    Column(
                      children: [
                        SingleChildScrollView(
                          controller: logic.scrollController,
                          padding: EdgeInsets.only(bottom: 10.w),
                          keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              _buildCarousel(),
                              _buildIndicator().center().paddingTop(12.w),
                              _buildTitle().padding(top: 15.w, horizontal: 16.w),
                              _buildDescription().padding(top: 15.w, horizontal: 16.w),
                              Row(
                                children: [
                                  logic.isTranslating
                                      ? SizedBox(
                                          width: 20.w,
                                          height: 20.w,
                                          child: CircularProgressIndicator(color: '#7DEDC9'.toColor, strokeWidth: 2.w),
                                        )
                                      : _buildTranslate(),
                                  const Spacer(),
                                  _buildPraise(),
                                ],
                              ).padding(top: 24.w, horizontal: 16.w),
                              if (controller.commentList.isNotEmpty) _Comment(controller).paddingTop(30.w),
                            ],
                          ),
                        ).expanded(),
                        _BottomInput(recordBar, logic),
                      ],
                    ),
                    _AppBar(bean),
                  ],
                ),
              );
            },
          );
        });
  }

  Widget _buildCarousel() {
    return CarouselWidget(
      items: (workBean.images ?? [])
          .map((e) => ImageWidget.asset('assets/ride_rex_images/$e', fit: BoxFit.cover))
          .toList(),
      currentIndex: controller.bannerCurrentIndex,
      onPageChanged: controller.onPageChanged,
      height: 210.w + ScreenUtil().statusBarHeight + 44,
      boxFit: BoxFit.cover,
      onTap: (index) {},
    );
  }

  Widget _buildIndicator() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 4.w),
      decoration: CommonDecoration.getShapeDecoration(bg: '#DDFFFF'.toColor.withOpacity(0.3), radius: 20),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: (workBean.images ?? []).map(
          (e) {
            int index = (workBean.images ?? []).indexOf(e);
            bool select = index == controller.bannerCurrentIndex;
            return Container(
              width: select ? 8.w : 4.w,
              height: 4.w,
              margin: EdgeInsets.only(right: index == (workBean.images ?? []).length - 1 ? 0 : 4.w),
              decoration: CommonDecoration.getShapeDecoration(
                bg: select ? null : '#CCCCCC'.toColor,
                gradient: select ? AppColors.primaryGradient : null,
                radius: 4.w,
              ),
            );
          },
        ).toList(),
      ),
    );
  }

  Widget _buildTitle() {
    return TextWidget.moreLine(
      text: controller.showTranslate ? controller.translateTitle : workBean.title,
      fontSize: 16,
      color: '#202020'.toColor,
    );
  }

  Widget _buildDescription() {
    return TextWidget.moreLine(
      text: controller.showTranslate ? controller.translateDescription : workBean.description,
      fontSize: 12,
      color: '#000000'.toColor.withOpacity(0.8),
    );
  }

  Widget _buildTranslate() {
    return ButtonWidget(
      onTap: controller.translate,
      hasInkWell: false,
      child: Row(
        children: [
          IconWidget.image(Assets.pngArticleTranslate, size: 16.w),
          TextWidget.oneLine(text: 'Translate', fontSize: 12, color: '#7DEDC9'.toColor).paddingLeft(7.w),
        ],
      ),
    );
  }

  Widget _buildPraise() {
    bool select = workBean.isLike == '1';
    return ButtonWidget.icon(
      IconWidget.image(select ? Assets.pngDiscoverPraiseSelect : Assets.pngDiscoverPraiseNormal, size: 34.w),
      onTap: () {
        if (workBean.workId.empty) return;
        if (select) {
          CommonLogic.cancelLike(recordId: workBean.workId!);
        } else {
          CommonLogic.like(recordId: workBean.workId!);
        }
      },
      hasInkWell: false,
    );
  }
}

class _Comment extends StatelessWidget {
  const _Comment(this.logic);

  final ArticleDetailLogic logic;

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildTitle(),
        ListView.separated(
          padding: EdgeInsets.zero,
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemCount: logic.commentList.length,
          itemBuilder: (BuildContext context, int index) {
            return _CommentItem(logic.commentList[index], logic);
          },
          separatorBuilder: (BuildContext context, int index) => CommonMargin.height(12.w),
        ).paddingTop(24.w),
      ],
    ).paddingHorizontal(20.w);
  }

  Widget _buildTitle() {
    String count = '';
    if (logic.commentList.isNotEmpty) count = '(${logic.commentList.length})';
    return TextWidget.oneLine(
      text: 'Comment$count',
      fontSize: 16,
      color: '#202020'.toColor,
      fontWeight: FontWeight.bold,
    );
  }
}

class _CommentItem extends StatelessWidget {
  const _CommentItem(this.bean, this.logic);

  final CommentBean bean;
  final ArticleDetailLogic logic;

  @override
  Widget build(BuildContext context) {
    bool isAudio = bean.audioFileName.notEmpty;
    return Container(
      decoration: CommonDecoration.getShapeDecoration(
        radius: 16.w,
        bg: '#E0FFF6'.toColor,
      ),
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              _buildAvatar(),
              _buildName().paddingLeft(10.w).expanded(),
              _buildPraise(),
            ],
          ),
          if (!isAudio) _buildContent().paddingTop(12.w),
          if (isAudio) _buildAudio().padding(top: 8.w, left: 48.w),
        ],
      ),
    );
  }

  Widget _buildAvatar() {
    return ImageWidget.url(bean.senderAvatar ?? '', width: 38.w, radius: 38.w);
  }

  Widget _buildName() => TextWidget.oneLine(
        text: bean.senderName,
        fontSize: 14,
        color: '#404040'.toColor,
        fontWeight: FontWeight.bold,
      );

  Widget _buildPraise() {
    bool isLike = bean.isLike == '1';
    return ButtonWidget.icon(
      IconWidget.image(isLike ? Assets.pngDiscoverPraiseSelect : Assets.pngDiscoverPraiseNormal, size: 24.w),
      onTap: () {
        if (bean.recordId.empty) return;
        if (isLike) {
          CommonLogic.cancelLike(recordId: bean.recordId!);
        } else {
          CommonLogic.like(recordId: bean.recordId!);
        }
      },
      hasInkWell: false,
    );
  }

  Widget _buildContent() {
    return TextWidget.moreLine(
      text: bean.text,
      fontSize: 12,
      color: '#404040'.toColor,
    );
  }

  Widget _buildAudio() {
    return ButtonWidget(
      onTap: () => logic.playAudio(bean),
      hasInkWell: false,
      child: Container(
        height: 28.w,
        width: 80.w,
        padding: EdgeInsets.symmetric(horizontal: 18.w),
        decoration: CommonDecoration.getShapeDecoration(radius: 28.w, bg: '#04A5FC'.toColor),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            bean.isPlaying
                ? Lottie.asset('assets/json/voice_black.json', width: 16.w, fit: BoxFit.cover)
                : IconWidget.image(Assets.pngArticlePlayAudio, size: 16.w, color: Colors.black),
            TextWidget.oneLine(text: '${bean.audioDuration}s', fontSize: 16, color: Colors.black).paddingLeft(8.w),
          ],
        ),
      ),
    );
  }
}

class _AppBar extends StatelessWidget {
  const _AppBar(this.bean);

  final FeedUserBean bean;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: CommonDecoration.getShapeDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          stops: const [0, 1],
          colors: [Colors.black.withOpacity(0.8), Colors.black.withOpacity(0)],
        ),
        radius: 0,
        borderColor: Colors.transparent,
        borderWidth: 0,
      ),
      height: ScreenUtil().statusBarHeight + 44,
      padding: EdgeInsets.only(top: ScreenUtil().statusBarHeight),
      child: Row(
        children: [
          _buildBack().paddingLeft(8),
          _buildAvatar(),
          _buildName().paddingLeft(10).expanded(),
          _buildMore().paddingRight(20),
        ],
      ),
    );
  }

  Widget _buildBack() {
    return ButtonWidget.icon(
      Assets.svgAppbarBack.toSvg(width: 20, color: Colors.white),
      onTap: CommonRoute.close,
      hasInkWell: false,
      padding: const EdgeInsets.all(12),
    );
  }

  Widget _buildAvatar() => Stack(
        alignment: Alignment.bottomRight,
        children: [
          ButtonWidget(
            hasInkWell: false,
            onTap: () => CommonRoute.open(PersonDetailPage(bean)),
            child: ImageWidget.url(
              bean.avatar ?? '',
              width: 40,
              height: 40,
              radius: 40,
              borderColor: Colors.white,
              borderWidth: 1,
            ),
          ),
          if (bean.isFriend == false)
            ButtonWidget(
              onTap: () async {
                if (bean.userId.empty) return;
                Loading.show();
                await CommonLogic.follow(bean.userId!);
                Loading.toast('Follow success', closeLoading: true);
              },
              hasInkWell: false,
              child: const IconWidget.image(Assets.pngDiscoverAdd, size: 16),
            ),
        ],
      );

  Widget _buildName() => TextWidget.oneLine(text: bean.nickname ?? '', fontSize: 16, color: Colors.white);

  Widget _buildMore() {
    return ButtonWidget.icon(
      const IconWidget.image(
        Assets.pngDiscoverMore,
        size: 28,
      ),
      hasInkWell: false,
      onTap: () => CommonLogic.onTapMore(bean.userId ?? '', showFollow: bean.isFriend == false),
    );
  }
}

class _BottomInput extends StatelessWidget {
  const _BottomInput(this.recordBar, this.logic);

  final ChatVoiceRecordBar recordBar;

  final ArticleDetailLogic logic;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: CommonDecoration.getShadow(
        bg: Colors.white,
        radius: 0,
        shadowColor: Colors.black.withOpacity(0.06),
        borderWidth: 0,
        borderColor: Colors.transparent,
        shadowOffset: Offset(0, -5.w),
      ),
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.w),
      child: Row(
        children: [
          _buildAudio(),
          (logic.showInput ? _buildInput() : _buildSendAudio()).paddingHorizontal(24.w).expanded(),
          _buildSend(),
        ],
      ),
    );
  }

  Widget _buildAudio() {
    return ButtonWidget.icon(
      IconWidget.image(logic.showInput ? Assets.pngArticleSendAudio : Assets.pngArticleKeyboard, size: 32.w),
      onTap: () async {
        if (logic.showInput) {
          CommonPrivilegeStatus status = await CommonPrivilege.microphone();
          if (!status.result) {
            CommonDialogs.twoButton(
              title: status.title,
              description: status.message,
              cancelTitle: YlmGlobalConfig().actionSheetConfig.cancelTitle,
              confirmTitle: YlmGlobalConfig().actionSheetConfig.confirmTitle,
              onConfirm: () => CommonPrivilege.openSettings(),
            );
            return;
          }
        }
        logic.changeInput();
      },
      hasInkWell: false,
    );
  }

  Widget _buildSendAudio() {
    return recordBar;
  }

  Widget _buildInput() {
    return Container(
      decoration: CommonDecoration.getShapeDecoration(bg: '#F2F2F2'.toColor, radius: 100),
      child: TextField(
        controller: logic.commentController,
        style: const TextStyle(fontSize: 12, color: AppColors.text),
        decoration: InputDecoration(
          hintText: 'Enter your ideas...',
          hintStyle: TextStyle(fontSize: 12, color: Colors.black.withOpacity(0.3)),
          contentPadding: EdgeInsets.symmetric(vertical: 12.w, horizontal: 14.w),
          border: InputBorder.none,
          isCollapsed: true,
          enabledBorder: const UnderlineInputBorder(borderSide: BorderSide(color: Colors.transparent)),
          focusedBorder: const UnderlineInputBorder(borderSide: BorderSide(color: Colors.transparent)),
        ),
      ),
    );
  }

  Widget _buildSend() {
    return ButtonWidget.text(
      'Send',
      textColor: Colors.white,
      fontSize: 16,
      alignment: Alignment.center,
      width: 63.w,
      height: 32.w,
      borderRadius: 32.w,
      backgroundColor: AppColors.primary,
      onTap: logic.sendTextComment,
    );
  }
}
